package com.cm367.teamc.listener;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import com.cm367.teamc.session.UserSession;

public class LoginListener implements PhaseListener {

	private static final long serialVersionUID = 1L;

	@Override
	public void afterPhase(PhaseEvent pe) {
		;
	}

	@Override
	public void beforePhase(PhaseEvent pe) {
		FacesContext context = FacesContext.getCurrentInstance();
		String page = context.getViewRoot().getViewId();
		if (!page.equals("/index.xhtml") && !page.equals("/eLeaveLogin.xhtml")) {
			Application app = context.getApplication();
			UserSession session = (UserSession) app.evaluateExpressionGet(
					context, "#{userSession}", UserSession.class);
			if (session.getUserID() == null) {
				ViewHandler handler = app.getViewHandler();
				UIViewRoot viewRoot = handler.createView(context,
						"/eLeaveLogin.xhtml");
				context.setViewRoot(viewRoot);
			}
		}
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
